#include <libemb/BaseType.h>
#include <libemb/Tracer.h>
#include <libemb/ArgUtil.h>
#include <libemb/Socket.h>
#include <libemb/Thread.h>
#include <libembx/HttpServer.h>
#include <libembx/HttpRequest.h>

using namespace libemb;
using namespace libembx;
//--------------------------------HTTP Server-------------------------------------
void TestHttpServer(void)
{
	InputReader reader;
	Thread severThread;
    HttpServer server;
    server.setRootPath("cgi-bin/");
    TRACE_YELLOW("config http server port:");
    reader.waitInput();
    uint16 port = reader.asInt();
    if(!server.setup("0.0.0.0",port))
    {
        TRACE_ERR("http server init failed.");
        return;
    }
    while (1) 
    {
        TRACE_YELLOW("-------http server test------.");
        TRACE_YELLOW("quit/q ---> quit test.");
        TRACE_YELLOW("start  ---> start server.");
        TRACE_YELLOW("stop   ---> stop server.");
        reader.waitInput();
        if (reader.isString("q") || reader.isString("quit"))
        {
            break;
        }
        else if(reader.isString("start"))
        {
            severThread.start(server);
            continue;
        }
        else if(reader.isString("stop"))
        {
            severThread.stop();
            continue;
        }
    }
    severThread.stop();
}


//--------------------------------HTTP Client-------------------------------------
#ifdef OS_CYGWIN
void TestHttpClient(void)
{
	TRACE_ERR("Not support HttpClient.");
}
#else
static void testHttpGet()
{
    HttpRequest client;
    File file;
    file.open("baidu.html", IO_MODE_REWR_ORNEW);
    client.getRequest("www.baidu.com",file);
    TRACE_YELLOW("HTTP GET OK!");
}

static void testHttpPost()
{
    HttpRequest client;
    File file;
    file.open("post.html",IO_MODE_REWR_ORNEW);
    client.postRequest("http://192.168.29.233:8080/cgi-bin/loginpage.cgi",\
                     "user=admin&passwd=123456&login=login", file);
    TRACE_YELLOW("HTTP POST OK!");
}

static void testFileDownLoad()
{
    HttpRequest client;
    File file;
    file.open("download.file",IO_MODE_REWR_ORNEW);
    client.fileRequest("http://", file);
    TRACE_YELLOW("HTTP File Download OK!");
}

void TestHttpClient(void)
{
    while (1)
    {
        TRACE_YELLOW("----HttpClient Test----");
        TRACE_YELLOW("01 test http get.");
        TRACE_YELLOW("02 test http post.");
        TRACE_YELLOW("03 test file download.");
        TRACE_YELLOW("please input:");
        InputReader reader;
        if (reader.isString("q")|| reader.isString("quit")) return;
        else if (reader.isString("01")) testHttpGet();
        else if (reader.isString("02")) testHttpPost();
        else if (reader.isString("03")) testFileDownLoad();
        else
        {
        }
    }
}
#endif
